import { deepClone } from '@/utils/utils'

const common = {
  state: {
    chatList: [],
    currentChat: -1
  },
  // 对state数据处理
  mutations: {
    CHANGE_CHATLIST: (state, chat) => {
      // Todo
      const current = state.chatList.findIndex(item => item.id === chat.id)
      if (current < 0) {
        state.chatList.unshift({
          id: chat.id,
          nickname: chat.nickname,
          avatar: chat.avatar,
          messages: []
        })
      } else {
        const temp = deepClone(state.chatList[current])
        state.chatList.splice(current, 1)
        state.chatList.unshift(temp)
      }
    },
    SET_CURRENTCHAT: (state, current) => {
      state.currentChat = current
    },
    SAVE_MESSAGE: (state, { id, message }) => {
      console.log(id, message)
      const current = state.chatList.findIndex(item => item.id === id)
      console.log(state.chatList[current].message)
      state.chatList[current].messages.push(message)
    }
  },
  actions: {
    AddChatList ({ commit }, chat) {
      commit('SET_CURRENTCHAT', chat.id)
      commit('CHANGE_CHATLIST', chat)
    },
    SetCurrent ({ commit }, id) {
      commit('SET_CURRENTCHAT', id)
    },
    SendMessage ({ commit }, { id, message }) {
      commit('SAVE_MESSAGE', { id, message })
    }
  }
}
export default common
